﻿using Pay.Common;
using Pay.Configuration;
using Pay.Core.exception;
using Pay.Core.models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Filters;

namespace Pay.Api.App_Start
{
    public class ApiResultAttribute:System.Web.Http.Filters.ActionFilterAttribute
    {
        private void ResultFormat(HttpActionExecutedContext actionExecutedContext, HttpStatusCode httpStatusCode, object resultObj)
        {
            var keyValue = actionExecutedContext.ActionContext.Request.GetQueryNameValuePairs().FirstOrDefault(s => s.Key == "callback");
            if (keyValue.Value != null && keyValue.Value != "")
            {
                actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(httpStatusCode, "");
                actionExecutedContext.Response.Content = new StringContent($"{keyValue.Value}({JsonHelper.SerializeObject(resultObj)})");
            }
            else
            {
                actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(httpStatusCode, resultObj);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);

            // 判断是否有异常,如果没有异常执行正常逻辑,如果出现任何异常,进入异常处理逻辑
            if (actionExecutedContext.Exception == null)
            {
                // 定义返回模型
                var result = new ApiOutput();
                result.Success = true;
                // 取得由 API 返回的状态代码
                result.Status = actionExecutedContext.ActionContext.Response.StatusCode;

                if (actionExecutedContext.ActionContext.Response.Content == null)
                {
                    result.Status = System.Net.HttpStatusCode.OK;
                    ResultFormat(actionExecutedContext, result.Status, result);
                }
                else
                {
                    if (actionExecutedContext.ActionContext.Response.Content.Headers.ContentType.MediaType == "application/json")
                    {
                        // 取得由 API 返回的资料
                        result.Data = actionExecutedContext.ActionContext.Response.Content.ReadAsAsync<object>()?.Result;
                        ResultFormat(actionExecutedContext, result.Status, result);
                    }
                }
            }
            else
            {
                // 定义返回模型
                var result = new ApiOutputExt();
                result.Success = false;
                // 取得由 API 返回的状态代码,如果是自定义异常,返回200,因为里面包含的信息通常为自定义错误提示或者有用信息
                result.Status = System.Net.HttpStatusCode.OK;
                var showErrorDetail = Config.GetValue("api:showErrorDetail");

                // 如果是项目自定义异常,需要取出自定义错误内容
                if (actionExecutedContext.Exception is LotException)
                {
                    var exception = actionExecutedContext.Exception as LotException;
                    result.Exception = exception;
                    result.Message = exception.ErrorMessage;
                    ResultFormat(actionExecutedContext, result.Status, result);
                }
                else
                {
                    result.Exception = actionExecutedContext.Exception;

                    // 如果是系统异常,返回500错误代码
                    //result.Status = System.Net.HttpStatusCode.InternalServerError;
                    result.Status = System.Net.HttpStatusCode.OK;
                    result.Message = actionExecutedContext.Exception.Message;

                }
                if (showErrorDetail?.ToLower() == "true")
                {
                    ResultFormat(actionExecutedContext, result.Status, result);
                }
                else
                {
                    result.Exception = null;
                    if (!(actionExecutedContext.Exception is LotException))
                    {
                        result.Message = "数据异常";
                    }
                    ResultFormat(actionExecutedContext, result.Status, result);
                }
            }
        }
    }
}